import * as types from '../action-types';
import {delay, take, takeEvery, put, all, call, fork, cancel, cancelled} from 'redux-saga/effects';
import Api from '../Api'

function* login(username: string, password: string) {
  try {
    yield put({type:types.SET_LOADING, payload:true})
    const token = yield call(Api.login, username, password);
    yield put({
      type: types.LOGIN_SUCCESS
      , payload: token
    });
    //把token也放置到localstorage里一份
    Api.set('token', token);
    // yield put({type:types.SET_LOADING, payload:false})
  }catch (error) {
    // yield put({type:types.SET_LOADING, payload:false})
    alert(error);
    yield put({
      type:types.LOGIN_ERROR
      ,error
    })
  }finally {
    if (yield cancelled()/*本任务被取消触发 即本generator在被fork的情况下其返回句柄被外层genrator cancel掉时触发*/) {
      alert('此任务是被取消了')
    }
    yield put({type:types.SET_LOADING, payload:false})
  }
}

//导出一个saga函数,里面放置着我们的流程
export function* loginFlow(){
  while(true){
    let action = yield take(types.LOGIN_REQUEST);
    const {username, password} = action;
    //fork就是相当于开启了一个新的进程,新的任务去运行,不会阻塞当前的saga,会立即返回一个代表当前进程的task对象
    const task = yield fork(login, username, password);
    action = yield take([types.LOGOUT_REQUEST/*take一个数组就是或的意思*/,types.LOGIN_ERROR]); //action={type:LOGOUT_REQUEST}
    if(action.type === types.LOGOUT_REQUEST){ //我们有可能点了登录 但又返回了 这个时候就需要取消掉之前fork出去的进程
      yield cancel(task)
    }
    Api.clear('token');
    yield put({
      type: types.LOGOUT_SUCCESS //清掉token
    });
  }
}
